package com.swift.authority.security.service.impl;

import com.swift.authority.common.constant.CommonConstant;
import com.swift.authority.common.util.StringUtil;
import com.swift.authority.core.user.response.UserRes;
import com.swift.authority.service.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 * @version 1.0
 * @description 自定义登录逻辑
 * @date 2022/06/25  17:12
 */
@Service
public class UserDetailsServiceImpl   implements UserDetailsService {
    private Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("开始处理用户登录校验 ...");
        UserRes userRes = userService.queryUserByUserName(username);
        String name = userRes.getUsername();
        if(StringUtil.isBlank(name) || !name.equals(username)){
            throw new UsernameNotFoundException("The username not exist,{}",new Throwable());
        }
        //注册时需要加密，所以用户需要先注册，所以需要先判断用户是否是注册业务 密码加密的盐
        String password = passwordEncoder.encode(CommonConstant.PWD_SALT);
        return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }

}
